package com.itbac.config.feign;

import feign.Feign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

/**
 * 解决 FeignClient 接口 被重复映射 springmvc 的问题。
 * @author: BacHe
 * @email: 1218585258@qq.com
 * @Date: 2021/4/22 20:56
 */
@Configuration
@Slf4j
@ConditionalOnClass(Feign.class)
public class FeignConfig implements WebMvcRegistrations{

    //类初始化时,创建新的 RequestMappingHandlerMapping
    private RequestMappingHandlerMapping requestMappingHandlerMapping = new FeignRequestMappingHandlerMapping();

    @Override
    public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
        return this.requestMappingHandlerMapping;
    }
    //新建 静态内部类
    private static class FeignRequestMappingHandlerMapping extends RequestMappingHandlerMapping{

        @Override
        protected boolean isHandler(Class<?> beanType) {
            /**
             * 新增排除 FeignClient 的逻辑
             * 1.有FeignClient
             * 2.没有Component
             */
            boolean feignClient = AnnotatedElementUtils.hasAnnotation(beanType, FeignClient.class) &&
                    !AnnotatedElementUtils.hasAnnotation(beanType, Component.class);
            if (feignClient){
                return false;
            }
            //使用原逻辑
           return  super.isHandler(beanType) ;
        }
    }
}
